/**
  * Created by Joshua Conero(O'Uymas) on 2016/11/7 0007.
  * QQ: 957376074
  * E-mail: Brximl@163.com
  */
import java.sql.{Connection, DriverManager, ResultSet}
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
class model (driver:String,dsn:String,username:String,pswd:String){
  /*
  // Change to Your Database Config
  val dsn = "jdbc:mysql://localhost:3306/cro2?user=root&password=151001"
  //Class.forName(driver)
  // Load the driver
  //classOf[com.mysql.jdbc.Driver]
  Class.forName("com.mysql.jdbc.Driver").newInstance()
  val con = DriverManager.getConnection(dsn)
  //val con = DriverManager.getConnection("jdbc:mysql://localhost/cro2","root", "151001")
  val db = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
  val rs = db.executeQuery("select `user_name` as 'name' from net_user")
  while(rs.next){
    println(rs.getString("name"))
  }
  */
  //classOf.forName(drv).newInstance()
  Class.forName(driver)
  val con = DriverManager.getConnection(dsn,username,pswd)
  val db = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)

  def table(tb:String):Unit ={
    val rs = db.executeQuery("select * from "+tb)
    val rsmd = rs.getMetaData()
    val cLen = rsmd.getColumnCount()
    val buffer = new ArrayBuffer[mutable.HashMap[String, Any]]()
    while (rs.next()){
      val map = mutable.HashMap[String, Any]()
      var retStr = ""
      for(i <- 1 to cLen) {
        map += (rsmd.getColumnLabel(i) -> rs.getString(i))
        retStr += rs.getString(i)+","
      }
      println(retStr)
      retStr = ""
      buffer += map
    }
    //println(buffer)
  }
  // 增删改处理
  def update(sql:String):Int = {
    val rs = db.executeUpdate(sql)
    if(!rs.isInstanceOf[Int]) return 0
    return rs
  }
}

